package com.example.wxsmart.resources;

import com.example.wxsmart.pojo.FileDetailEntity;
import com.example.wxsmart.util.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author Luojunxian
 * @data 2022/5/30 11:15
 * @classname IkFileResourse
 */
@Slf4j
@Component
public class IkFileResources {

    /**
     * 读取
     *
     * @param file 文件
     * @return {@code FileDetailEntity}
     */
    public FileDetailEntity read(File file) {
        if (!file.exists()) {
            try {
                log.info("文件不存在,创建文件{}", file.getAbsolutePath());
                file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException("创建file:" + file.getAbsolutePath() + "失败");
            }
        }

        ArrayList<String> result = new ArrayList<>();

        // 打开输出流
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        try {
            fileReader = new FileReader(file);

            bufferedReader = new BufferedReader(fileReader);

            String read;

            while (null != (read = bufferedReader.readLine())) {
                result.add(read);
            }

        } catch (IOException e) {
            throw new RuntimeException("file路径有误");
        } finally {
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != fileReader) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        FileDetailEntity fileDetail = FileUploadUtil.getFileDetail(file);
        fileDetail.setFileContent(result);
        fileDetail.setFileRow(result.size());

        log.info("Ik:{}读取成功!读取数 {} 行", file.getName(), result.size());

        return fileDetail;
    }

    /**
     * 添加
     *
     * @param file   文件
     * @param values 值
     * @return {@code FileDetailEntity}
     */
    public FileDetailEntity add(File file, List<String> values) {
        List<String> list = duplicateRemoval(read(file).getFileContent(), values, true);
        log.info("Ik:{}修改成功!修改数 {} 行", file.getName(), list.size());
        return fileChanged(file, list, true);
    }

    /**
     * 删除
     *
     * @param file   文件
     * @param values 值
     * @return {@code FileDetailEntity}
     */
    public FileDetailEntity delete(File file, List<String> values) {
        List<String> oldValue = read(file).getFileContent();

        List<String> list = duplicateRemoval(oldValue, values, false);

        log.info("Ik:{}删除成功!删除数 {} 行", file.getName(), list.size());

        if (list.isEmpty()) {
            return fileChanged(file, list, false);
        }

        FileDetailEntity result = fileChanged(file, duplicateRemoval(values, oldValue, true), false);
        result.setFileContent(list);
        result.setFileRow(list.size());
        return result;
    }

    /**
     * 文件的curd
     *
     * @param file   文件
     * @param values 值
     * @param isAdd  是添加
     * @return {@code FileDetailEntity}
     */
    private FileDetailEntity fileChanged(File file, List<String> values, boolean isAdd) {
        if (!values.isEmpty()) {
            CompletableFuture.runAsync(() -> {
                try {
                    // 打开输入流
                    FileWriter fileWriter = new FileWriter(file, isAdd);

                    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

                    values.forEach(value -> {
                        try {
                            bufferedWriter.write(value);
                            bufferedWriter.newLine();
                            bufferedWriter.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });

                    bufferedWriter.close();
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }

        FileDetailEntity fileDetail = FileUploadUtil.getFileDetail(file);
        fileDetail.setFileContent(values);
        fileDetail.setFileRow(values.size());
        return fileDetail;
    }

    /**
     * newValues去重
     *
     * @param oldValues 旧值
     * @param newValues 新值
     * @param isRemove  是删除
     * @return {@code List<String>}
     */
    private List<String> duplicateRemoval(List<String> oldValues, List<String> newValues, boolean isRemove) {
        ArrayList<String> result = new ArrayList<>();

        newValues.forEach(newValue -> {
            if (isRemove == !oldValues.contains(newValue)) {
                result.add(newValue);
            }
        });

        return result;
    }

}
